<template>
	<view >
		<!-- 搜索框 -->
		<uniSearchBar
			class="search-input"
			:style="searchBarPosition"
			:focus="true"
			:value="searchVal"
			placeholder="请输入搜索关键词"
			:radius="20"
			clearButton="none"
			cancelButton="none"
			@input="handleInput"
			@confirm="debounce(() => _searchPicture(true), 300)"
		>
		</uniSearchBar>
		<!-- 分页图片列表 -->
		<scroll-view
			class="pictrue-container"
			:scroll-y="true"
			scroll-with-animation="true"
			@scroll="handleScroll"
			@scrolltolower="onReachBottom"
		>
			<!-- 主图 -->
			<view class="main-pic" :style="mainPicStyle">
				<image
					mode="aspectFit"
					:style="mainPicStyle"
					:src="mainPic?.url || '#'"
				/>
			</view>
		  <view class="list-pic">
		    <view class="pics">
		      <view class="pics-content">
		        <view
		          v-for="(pics, index) of pictureList"
		          :key="index"
		          :style="{ 'margin-left': !index ? '' : '10rpx' }"
		          class="pic-row"
		        >
		          <view
		            v-for="(pic, ind) of pics"
		            :key="ind"
		            class="pic-item"
		            :style="{'padding-top': 1 / (pic.wh_radio - 0) * 100 + '%'}"
								@click="preview(pic)"
		          >
		            <span class="cover-div"></span>
		            <image
		              mode="aspectFit"
		              class="pic-item-content"
		              :src="pic?.url || '#'"
		            />
		          </view>
		        </view>
		      </view>
		    </view>
		  </view>
			<!-- 图片预览 -->
			<qPreviewImage
				ref="previewImage"
				:urls="previewPicture"
				@onLongpress="onLongpress"
				@open="open"
				@close="close"
			></qPreviewImage>
		</scroll-view>
	</view>
</template>

<script lang="ts" setup>
import { debounce } from "lodash";
import { nextTick, onMounted, ref } from "vue";
import { getMainPicture, searchPicture } from "../../service/index";
import { createModalComp, createToastComp } from "../../utils/comp";
import { uniSearchBar } from '@/uni_modules/uni-ui/components/uni-search-bar/uni-search-bar.vue';
import { qPreviewImage } from "@/uni_modules/q-previewImage/components/q-previewImage/q-previewImage.vue";

const searchVal = ref(""); // 搜索框内容
const pageNumber = ref(1); // 图片当前页
const pageSize = ref(10); // 页大小
const pageCount = ref(1); // 总页数
const total = ref(1); // 总大小
const pictureList = ref([]); // 图片列表
const mainPic = ref(null); // 主图
const mainPicStyle = ref("width: 100%; height: ");

const previewImage = ref(null);
const previewPicture = ref([]); // 预览图片列表

// 获取到小程序全局唯一的 App 实例，向实例中定义属性
// fixed首次打开不显示标题的bug
getApp().configLoadOK = () => {
  uni.setNavigationBarTitle({ // 动态设置当前页面的标题
    title: uni.getStorageSync('projectName')
  })
}

// 搜索框的定位
const searchBarPosition = ref({
	top: "32px",
	left: "50%",
	transform: "translate(-50%, 0)",
});

// 搜索框的响应式
const handleInput = (e: any) => {
	searchVal.value = e.value;
};

// 动态处理输入框的定位
const handleScroll = (e: any) => {
	const { scrollTop } = e.detail;
	searchBarPosition.value.top = scrollTop > 30 ? "2px" : "32px";
};

// 滚动到最底部时
const onReachBottom = debounce(() => {
	if (pageNumber.value < pageCount.value) {
		pageNumber.value++;
		_searchPicture();
	} else {
		createToastComp({ title: "到底了" }, "success");
	}
}, 300);

// Vue 3的Composition API和uni-app生命周期一起使用的方式
const page = getCurrentPages()?.find(i => i.route === "pages/index/index");
page && (page.onLoad = function(e: any) {
	uni.showShareMenu({
		withShareTicket: true
	})
	// 读取分享链接中的邀请人编号
	if (e && e.inviter_id) {
		uni.setStorageSync('referrer', e.inviter_id)
	}
	// 读取小程序码中的邀请人编号
	if (e && e.scene) {
		const scene = decodeURIComponent(e.scene)
		if (scene) {        
			uni.setStorageSync('referrer', scene.substring(11));
		}
	}
});

const getMainPic = async () => {	
	try{
		const res: any = await getMainPicture({});
		if (res.status === "success") {
			mainPic.value = res?.data?.[0] || {},
			// 设置主图样式
			uni.getSystemInfo({
				success: res => {
					let tempStr = "width: 100%; height: ";
					if (!mainPic.value?.wh_radio || !res.windowWidth) {
						tempStr += "200px";
					}
					tempStr += ((res.windowWidth / mainPic.value.wh_radio).toFixed(0) + "px");
					mainPicStyle.value = tempStr;
				}
			});
		} else {
			createModalComp({
				content: "请在后台添加/设置主图",
				showCancel: false,
			})
		}
	}catch(e){
		//TODO handle the exception
	}
};

/**
 * 分页查询所有图片
 */
const _searchPicture = async (reset = false) => {	
	if (reset) {
		total.value = 0;
		pageCount.value = 0;
		pageNumber.value = 1;
	}
	const params: any = {
		pageNumber: pageNumber.value,
		pageSize: pageSize.value,
		searchVal: searchVal.value || "",
		orders: {
			column: "capture_time",
			order: "desc",
		}
	};
	const res: any = await searchPicture(params);
	if (res.status === "success") {
		const dataList = res?.data?.list || [];
		// 处理图片格式
		total.value = res?.data?.total || 0,
		pageCount.value = Math.ceil((res?.data?.total || 0) / res?.data?.pageSize)
		let firstColumn = []; // 第一列
		let secondColumn = []; // 第二列
		let previewColumn = []; // 预览列表
		if (pageNumber.value > 1) {
			firstColumn = pictureList.value[0]; // 第一列
			secondColumn = pictureList.value[1]; // 第二列			
			previewColumn = previewPicture.value;
		}
		dataList.forEach((item: any, index: number) => {
			if ((index + 1) % 2 === 1) {
				firstColumn.push(item);
			} else if ((index + 1) % 2 === 0) {
				secondColumn.push(item);
			}
		});
		pictureList.value = [firstColumn, secondColumn];
		previewColumn.push(...dataList.map((i: any) => i.url));
		previewPicture.value = previewColumn;
	} else {
		createToastComp({ title: res.msg || "错误" }, "error");
	}
};

onMounted(() => {
	getMainPic();
	_searchPicture();
});

const preview = (item: any) => {
	if (!item.url || item.url === "#") return;
	// #ifdef MP-WEIXIN
	nextTick(() => {
		previewImage.value.open(item.url); // 传入当前选中的图片地址(小程序必须添加$nextTick，解决组件首次加载无图)
	});
	// #endif
	// #ifndef MP-WEIXIN
	previewImage.value.open(item.url); // 传入当前选中的图片地址
	// #endif
};

const onLongpress = (url: any) => {
	// TODO：暂未实现
	// uni.showActionSheet({
	// 	itemList: ['转发给朋友', '保存到手机'],
	// 	success: function (res) {
	// 		console.log('选中了第' + (res.tapIndex + 1) + '个按钮');
	// 	},
	// 	fail: function (res) {
	// 		console.log(res.errMsg);
	// 	}
	// });
}

/* open和close方法一般用不到，但是在一些特殊场景会用到，
* 比如预览图片时你需要覆盖 NavigationBar和 TabBar，
* 或者在app中需要预览图片时覆盖住原生组件，比如video或者map等，
* 你可以根据open和close去做一些操作，例如隐藏导航栏或者隐藏一些原生组件等
*/
const open = () => { //监听组件显示 （隐藏TabBar和NavigationBar，隐藏video原生组件）
	// uni.hideTabBar()
	// uni.setNavigationBarColor({
	//  frontColor: '#000000', // 设置前景色为黑色
	//  backgroundColor: '#000000', // 设置背景色为黑色
	// })
	// data.videoShow = false 
}

const close = () => { //监听组件隐藏 （显示TabBar和NavigationBar，显示video原生组件）
	// uni.showTabBar()
	// uni.setNavigationBarColor({
	//  frontColor: '#ffffff', // 设置前景色为白色
	//  backgroundColor: '#000000', // 设置背景色为黑色
	// })
	// data.videoShow = true
}
</script>

<style lang="less" scoped>
.search-input {
  position: absolute;
  z-index: 1;
  width: 75vw;
	transition: top .2s cubic-bezier(0.215, 0.610, 0.355, 1);
	> :deep(view ) {
		background: none !important;
		padding: 0 !important;
	}
}

.pictrue-container {
	height: 100vh;
	overflow: auto;
	.main-pic {
		width: 750rpx;
		position: relative;
		filter: opacity(0.7);
	}
	.list-pic {
		color: #656f79;
		width: 100%;
		display: inline-block;
		overflow: auto;
		padding: 8rpx;
		box-sizing: border-box;
		.pics {
		  margin-bottom: 20rpx;
		  position: relative;
		}
	}
}

.pics-content {
  display: flex;
  align-items: flex-start;
  overflow: hidden;
  width: 100%;
}
.pic-row {
  flex: 1;
}
.pic-item {
  margin-bottom: 10rpx;
  position: relative;
  cursor: pointer;
}
.pic-item .cover-div {
  display: block;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  filter: opacity(0.3);
  background-color: #0f0186;
  border-radius: 14rpx;
}
.pic-item-content {
  height: 100%;
  width: 100%;
  overflow: hidden;
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  border-radius: 14rpx;
}
.pic-item-content > img {
  width: 100%;
  height: 100%;
  max-width: 100%;
  max-height: 100%;
}
.pic-item-content > img .overlay {
  opacity: 0;
  transition: all 0.25s;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  cursor: pointer;
  pointer-events: none;
}
.pic-item-content > img .overlay-controls {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  padding: 16rpx;
  background: linear-gradient(
    180deg,
    rgba(25, 27, 38, 0.56),
    rgba(25, 27, 38, 0)
  );
  display: flex;
  align-items: center;
  justify-content: flex-start;
  gap: 8rpx;
  cursor: pointer;
  pointer-events: auto;
}
.left-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32rpx;
  height: 32rpx;
  border-radius: 8rpx;
  border: 1rpx solid hsla(0, 0%, 100%, 0.4);
  background: hsla(0, 0%, 100%, 0.1);
  color: #fff;
  text-decoration: none;
  cursor: pointer;
  font-size: 20rpx;
}
.pic-item-content > img .overlay-bottom {
  position: absolute;
  display: flex;
  gap: 8rpx;
  left: 0;
  bottom: 0;
  width: 100%;
  padding: 16rpx;
  background: linear-gradient(
    180deg,
    rgba(25, 27, 38, 0),
    rgba(25, 27, 38, 0.56)
  );
  cursor: pointer;
  pointer-events: auto;
  color: hsla(0, 0%, 100%, 0.8);
}
</style>
